<template>
	<view class="content">
		<Multiple></Multiple>
		<Title title="为你优选"></Title>
		<Preference :preferdata="preferdata"></Preference>
		<Title title="附近商家"></Title>
		<Delicacy id="delicacy" :class="{is_fixed: sortFixed}" @click.native="backToTop"></Delicacy>
		<Takeout class="take-out" :shopList="sortData.nearlyShop"></Takeout>
	</view>
</template>

<script>
	import Multiple from './components/Multiple.vue'
	import Preference from './components/Preference.vue'
	import Delicacy from './components/Delicacy.vue'
	import Takeout from './components/Takeout.vue'
	import Title from '../../components/content/Title.vue'

	import {
		getPerference,
		getNearlyShop
	} from '../../network/home.js'

	import {mapState, mapMutations} from 'vuex'
	export default {
		components: {
			Multiple,
			Preference,
			Delicacy,
			Takeout,
			Title
		},
		computed: {
			// 筛选出的商家数据
			...mapState(['sortData'])
		},
		data() {
			return {
				preferdata: [],
				nearlyShopList: [],
				delicacyTop: null,
				sortFixed: false	,
				currScrollTop: 0,
				scrollTop: null
			}
		},
		// 监听属性
		watch: {
			// 监听筛选组件置顶和不置顶
			scrollTop() {
				// 如果页面滚动的高度大于筛选组件距离顶部的高度，那就置顶，反之不置顶
				if (this.scrollTop > this.delicacyTop) {
					this.sortFixed = true
				} else {
					this.sortFixed = false
				}
			}
		},
		onLoad() {
			this.requestData()
		},
		onReady() {
			// 监听筛选组件距离顶部的距离
			const query = uni.createSelectorQuery()
			query.select('#delicacy').boundingClientRect()
			query.exec((res) => {
				this.delicacyTop = res[0].top
			})
			// 获取当前滚动距离
			// #ifdef H5
			this.currScrollTop = document.body.scrollTop || document.documentElement.scrollTop
			// #endif
		},
		// 监听页面滚动距离
		onPageScroll(e) {
			this.scrollTop = e.scrollTop - this.currScrollTop
		},
		methods: {
			// 存储附近商家数据
			...mapMutations(['setNearlyShop']),
			// 回到顶部
			backToTop() {
				uni.pageScrollTo({
					scrollTop: this.delicacyTop + this.currScrollTop,
					duration: 150
				})
			},
			// 并发请求数据
			requestData() {
				// 为你优选数据
				let perference = getPerference()
				// 附近商家数据
				let nearlyShop = getNearlyShop()
				let requestArr = [perference, nearlyShop]
				Promise.all(requestArr.map(promise =>
					promise.catch(e => {
						console.log(e)
					})
				)).then(res => {
					this.preferdata = res[0].data || []
					this.setNearlyShop(res[1].data)
				})
			}
		}
	}
</script>

<style scoped>
	.content {
		margin: 0 15rpx;
	}

	.is_fixed {
		position: fixed;
		left: 0;
		/* #ifdef H5 */
		top: 88upx;
		/* #endif */
		/* #ifdef MP-WEIXIN */
		top: 0;
		/* #endif */
		right: 0;
	}

	.take-out {
		box-sizing: border-box;
		min-height: 100vh;
		padding-top: 70upx;
	}
</style>
